<?php

namespace app\shop\model\store;

use app\common\model\store\Store as StoreModel;
use app\common\model\store\StoreLook as StoreLookModel;
use Lvht\GeoHash;

/**
 * 门店模型
 */
class StoreLook extends StoreLookModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'app_id',
        'update_time',
    ];

    /**
     * 获取列表数据
     */
    public function getList($data = null, $status = '')
    {
        $model = $this;
        !empty($status) && $model = $model->where('status', '=', (int)$status);
        $data['check_store'] != '' && $model = $model->where('check_store', '=', $data['check_store']);
        $list = $model->with(['logo', 'supplier'])->where('is_delete', '=', '0')
            ->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->paginate($data);
        return $list;
    }

    /**
     * 获取所有门店列表
     */
    public static function getAllList()
    {
        return (new self)->where('is_delete', '=', '0')
            ->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->select();
    }

    /**
     * 新增记录
     */
    public function add($data)
    {
        $data = $this->createData($data);
        return self::create($data);
    }

    /**
     * 编辑
     * edit
     * @param $data
     * StoreModel|true
     * @return StoreModel|true
     * @Author kevin
     * @date 2024/5/21 11:12
     */
    public function edit($data)
    {
        $data = $this->createData($data);
        if($this->save($data)){
            $store_id = $data['store_id'];
            unset($data['store_id'],$data['store_look_id'],$data['coordinate']);
            if($data['check_store'] == 1){ //审核通过再更新到主表
                $data['scope_coordinates'] = json_encode($data['scope_coordinates']);
                return (new StoreModel()) -> where('store_id',$store_id) -> update($data);
            }
        }
        return true;
    }

    /**
     * 软删除
     */
    public function setDelete($where)
    {

        if(self::update(['is_delete' => 1], $where)){
            //删除表数据的同时也要删除主表的数据
            return (new StoreModel()) -> update(['is_delete' => 1], $where);
        }
    }

    /**
     * 创建数据
     */
    private function createData($data)
    {
        $data['app_id'] = self::$app_id;
        // 格式化坐标信息
        $coordinate = explode(',', $data['coordinate']);
        $data['latitude'] = $coordinate[0];
        $data['longitude'] = $coordinate[1];

        // 生成geohash
        $Geohash = new Geohash;
        $data['geohash'] = $Geohash->encode($data['longitude'], $data['latitude']);
        return $data;
    }

}
